package info.batcloud.fanli.core.action;

import info.batcloud.fanli.core.action.domain.UserActivationAction;
import info.batcloud.fanli.core.entity.User;
import info.batcloud.fanli.core.entity.UserMission;
import info.batcloud.fanli.core.enums.MissionType;
import info.batcloud.fanli.core.enums.UserMissionStatus;
import info.batcloud.fanli.core.enums.WalletFlowDetailType;
import info.batcloud.fanli.core.repository.UserMissionRepository;
import info.batcloud.fanli.core.repository.UserRepository;
import info.batcloud.fanli.core.service.WalletService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.Date;
import java.util.List;

@Component
public class UserActivationActionInspector extends AbstractActionInspector<UserActivationAction> {

    @Inject
    private UserMissionRepository userMissionRepository;

    @Inject
    private UserRepository userRepository;

    @Inject
    private WalletService walletService;

    @Override
    @Transactional
    public void inspect(UserActivationAction mission) {
        //处理用户邀请任务
        List<UserMission> userMissionList
                = userMissionRepository.findByUserIdAndMissionTypeAndStatus(mission.getSuperUserId(), MissionType.USER_INVITATION, UserMissionStatus.IN_PROGRESS);
        for (UserMission userMission : userMissionList) {
            userMission.setCompleteTimes(userMission.getCompleteTimes() + 1);
            User user = userRepository.findOne(mission.getUserId());
            if (userMission.getCompleteTimes() == userMission.getMission().getTotalTimes()) {
                userMission.setStatus(UserMissionStatus.COMPLETE);
                userMission.setCompleteTime(new Date());
                //如果任务已经完成，增加用户积分
                walletService.addIntegral(mission.getSuperUserId(), userMission.getMission().getIntegral(),
                        WalletFlowDetailType.USER_INVITATION, new String[]{user.getNickname()});
            }
            userMissionRepository.save(userMission);
        }

    }

    @Override
    public Class<UserActivationAction> getMissionClass() {
        return UserActivationAction.class;
    }
}
